<template>
  <a-drawer
    :title="title"
    :maskClosable="true"
    width=650
    placement="right"
    :closable="true"
    @close="close"
    :visible="visible"
    style="overflow: auto;padding-bottom: 53px;">

    <a-form>
      <a-form-item label='所拥有的权限'>
        <a-alert v-if="!isAdmin" message="提示：非管理员用户只能分配自己拥有的菜单和按钮权限" type="warning" show-icon style="margin-bottom: 10px"/>
        <div v-if="treeData.length === 0" style="text-align: center; padding: 20px;">
          <a-empty description="暂无可配置权限" />
        </div>
        <a-tree
          v-else
          checkable
          @check="onCheck"
          :checkedKeys="checkedKeys"
          :halfCheckedKeys="halfCheckedKeys"
          :treeData="treeData"
          @expand="onExpand"
          @select="onTreeNodeSelect"
          :selectedKeys="selectedKeys"
          :expandedKeys="expandedKeysss"
          :checkStrictly="checkStrictly">
          <span slot="hasDatarule" slot-scope="{slotTitle,ruleFlag}">
            {{ slotTitle }}<a-icon v-if="ruleFlag" type="align-left" style="margin-left:5px;color: red;"></a-icon>
          </span>
        </a-tree>
      </a-form-item>
    </a-form>

    <div class="drawer-bootom-button">
      <a-dropdown style="float: left" :trigger="['click']" placement="topCenter">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="switchCheckStrictly(1)">父子关联</a-menu-item>
          <a-menu-item key="2" @click="switchCheckStrictly(2)">取消关联</a-menu-item>
          <a-menu-item key="3" @click="checkALL">全部勾选</a-menu-item>
          <a-menu-item key="4" @click="cancelCheckALL">取消全选</a-menu-item>
          <a-menu-item key="5" @click="expandAll">展开所有</a-menu-item>
          <a-menu-item key="6" @click="closeAll">合并所有</a-menu-item>
        </a-menu>
        <a-button>
          树操作 <a-icon type="up" />
        </a-button>
      </a-dropdown>
      <a-popconfirm title="确定放弃编辑？" @confirm="close" okText="确定" cancelText="取消">
        <a-button style="margin-right: .8rem">取消</a-button>
      </a-popconfirm>
      <a-button @click="handleSubmit(false)" type="primary" :loading="loading" ghost style="margin-right: 0.8rem">仅保存</a-button>
      <a-button @click="handleSubmit(true)" type="primary" :loading="loading">保存并关闭</a-button>
    </div>

    <role-datarule-modal ref="datarule"></role-datarule-modal>

  </a-drawer>

</template>
<script>
  import {queryTreeListForRole,queryRolePermission,saveRolePermission,queryPermissionsByUser,getCurrentUserRoles} from '@/api/api'
  import RoleDataruleModal from './RoleDataruleModal.vue'

  export default {
    name: "RoleModal",
    components:{
      RoleDataruleModal
    },
    data(){
      return {
        roleId:"",
        treeData: [],
        defaultCheckedKeys:[],
        checkedKeys:[],
        halfCheckedKeys:[],
        expandedKeysss:[],
        allTreeKeys:[],
        autoExpandParent: true,
        checkStrictly: true,
        title:"角色权限配置",
        visible: false,
        loading: false,
        selectedKeys:[],
        isAdmin: false,
        userPermissions: [] // 存储当前用户的权限
      }
    },
    methods: {
      onTreeNodeSelect(id){
        if(id && id.length>0){
          this.selectedKeys = id
        }
        this.$refs.datarule.show(this.selectedKeys[0],this.roleId)
      },
      onCheck (checked, e) {
        if(this.checkStrictly){
          this.checkedKeys = checked.checked;
          this.halfCheckedKeys = checked.halfChecked || [];
          console.log('选中的节点:', this.checkedKeys);
          console.log('半选中的节点:', this.halfCheckedKeys);
        }else{
          this.checkedKeys = checked;
        }
      },
      show(roleId){
        this.roleId=roleId
        this.visible = true;
      },
      close () {
        this.reset()
        this.$emit('close');
        this.visible = false;
      },
      onExpand(expandedKeys){
        this.expandedKeysss = expandedKeys;
        this.autoExpandParent = false
      },
      reset () {
        this.expandedKeysss = []
        this.checkedKeys = []
        this.halfCheckedKeys = []
        this.defaultCheckedKeys = []
        this.loading = false
        this.treeData = []
      },
      expandAll () {
        this.expandedKeysss = this.allTreeKeys
      },
      closeAll () {
        this.expandedKeysss = []
      },
      checkALL () {
        // 如果是管理员，可以全选所有权限
        // 如果不是管理员，只能全选自己拥有的权限
        if (this.isAdmin) {
          this.checkedKeys = this.allTreeKeys
        } else {
          this.checkedKeys = this.userPermissions.length > 0 ? this.userPermissions : this.allTreeKeys
        }
      },
      cancelCheckALL () {
        this.checkedKeys = []
      },
      switchCheckStrictly (v) {
        if(v==1){
          this.checkStrictly = false
        }else if(v==2){
          this.checkStrictly = true
        }
      },
      handleCancel () {
        this.close()
      },
      handleSubmit(exit) {
        let that = this;
        
        // 获取所有需要保存的权限ID
        let permissionIds = [...that.checkedKeys];
        
        // 如果存在halfCheckedKeys（父节点半选状态），也将其添加到保存列表中
        if (that.halfCheckedKeys && that.halfCheckedKeys.length > 0) {
          permissionIds = [...permissionIds, ...that.halfCheckedKeys];
        }
        
        // 去重
        permissionIds = [...new Set(permissionIds)];
        
        let params = {
          roleId: that.roleId,
          permissionIds: permissionIds.join(","),
          lastpermissionIds: that.defaultCheckedKeys.join(","),
        };
        
        that.loading = true;
        console.log("请求参数：", params);
        saveRolePermission(params).then((res)=>{
          if(res.success){
            that.$message.success(res.message);
            that.loading = false;
            if (exit) {
              that.close()
            }
          }else {
            that.$message.error(res.message);
            that.loading = false;
            if (exit) {
              that.close()
            }
          }
          this.loadData();
        })
      },
      // 过滤树形数据，只保留用户拥有权限的节点
      filterTreeData(treeData, userPermissions) {
        if (!treeData || treeData.length === 0) {
          return [];
        }

        return treeData.filter(node => {
          // 检查当前节点是否在用户权限中
          const hasPermission = userPermissions.includes(node.key);
          
          // 递归过滤子节点
          if (node.children && node.children.length > 0) {
            node.children = this.filterTreeData(node.children, userPermissions);
          }
          
          // 如果当前节点有权限或者子节点中有权限的节点，则保留
          return hasPermission || (node.children && node.children.length > 0);
        });
      },
      // 从接口返回数据中提取权限ID
      extractPermissionIds(data) {
        let ids = [];
        
        // 尝试处理不同的数据结构
        if (Array.isArray(data)) {
          // 如果是数组，直接提取ID
          ids = data.map(item => {
            if (typeof item === 'string') return item;
            return item.id || '';
          }).filter(id => id);
        } else if (data && typeof data === 'object') {
          // 如果是对象，尝试从不同属性中提取
          if (data.menu && Array.isArray(data.menu)) {
            ids = data.menu.map(item => item.id || '').filter(id => id);
          } else if (data.allAuth && Array.isArray(data.allAuth)) {
            ids = data.allAuth.map(item => item.id || '').filter(id => id);
          } else if (data.auth && Array.isArray(data.auth)) {
            ids = data.auth.map(item => item.id || '').filter(id => id);
          } else {
            // 尝试遍历对象的所有属性
            Object.values(data).forEach(value => {
              if (Array.isArray(value)) {
                const extracted = value.map(item => {
                  if (typeof item === 'string') return item;
                  return item.id || '';
                }).filter(id => id);
                ids = [...ids, ...extracted];
              }
            });
          }
        }
        
        return ids;
      },
      loadData(){
        // 检查当前用户是否为管理员
        this.isAdmin = this.$store.getters.userInfo.id === 'e9ca23d68d884d4ebb19d07889727dae';
        console.log('当前用户是否为超级管理员:', this.isAdmin);
        
        // 获取树形菜单数据
        queryTreeListForRole().then((res) => {
          if (!res.success) {
            this.$message.error('获取权限菜单失败');
            return;
          }
          
          // 获取所有菜单树和ID
          const allTreeData = res.result.treeList;
          this.allTreeKeys = res.result.ids;
          console.log('所有菜单树:', allTreeData);
          console.log('所有菜单ID:', this.allTreeKeys);
          
          if (this.isAdmin) {
            // 超级管理员可以看到所有菜单
            this.treeData = allTreeData;
            console.log('超级管理员，显示所有菜单');
            // 获取角色已有的权限
            this.loadRolePermissions();
          } else {
            // 非超级管理员，获取当前用户的角色信息
            getCurrentUserRoles().then(res => {
              if (res.success && res.result && res.result.length > 0) {
                // 获取当前用户的所有角色
                const userRoles = res.result;
                console.log('当前用户的角色列表:', userRoles);
                
                // 创建一个Promise数组，用于存储所有角色权限的请求
                const promises = userRoles.map(role => {
                  return new Promise((resolve) => {
                    queryRolePermission({roleId: role.id}).then(res => {
                      if (res.success && res.result) {
                        resolve(res.result);
                      } else {
                        resolve([]);
                      }
                    }).catch(() => {
                      resolve([]);
                    });
                  });
                });
                
                // 等待所有请求完成
                Promise.all(promises).then(results => {
                  // 合并所有角色的权限
                  let userPermissions = [];
                  results.forEach(result => {
                    userPermissions = [...userPermissions, ...result];
                  });
                  
                  // 去重
                  this.userPermissions = [...new Set(userPermissions)];
                  console.log('当前用户的所有角色权限ID:', this.userPermissions);
                  
                  if (this.userPermissions.length === 0) {
                    // 如果没有权限，显示空树
                    this.treeData = [];
                    console.log('当前用户没有任何菜单权限');
                  } else {
                    // 过滤树形数据，只保留用户拥有权限的节点
                    this.treeData = this.filterTreeData(allTreeData, this.userPermissions);
                    console.log('过滤后的菜单树:', this.treeData);
                  }
                  
                  // 获取角色已有的权限
                  this.loadRolePermissions();
                });
              } else {
                console.log('当前用户没有任何角色');
                this.treeData = [];
                // 获取角色已有的权限
                this.loadRolePermissions();
              }
            }).catch(err => {
              console.error('获取用户角色信息出错:', err);
              this.$message.error('获取用户角色信息失败');
              this.treeData = [];
              // 获取角色已有的权限
              this.loadRolePermissions();
            });
          }
        }).catch(err => {
          console.error('获取菜单树出错:', err);
          this.$message.error('获取权限菜单失败');
        });
      },
      loadRolePermissions() {
        //获取当前登录账号的角色id用于查询角色权限
        if (this.isAdmin) {
          // 超级管理员直接使用传入的角色ID
          queryRolePermission({roleId: this.roleId}).then((res)=>{
            console.log('角色权限响应:', res);
            if (res.success && res.result) {
              // 保存所有权限ID
              const allPermissions = [...res.result];
              this.defaultCheckedKeys = [...allPermissions];
              
              // 初始化展开所有节点
              this.expandedKeysss = this.allTreeKeys;
              
              // 在 checkStrictly 模式下，不需要区分半选状态，直接设置所有节点为选中
              this.checkedKeys = allPermissions;
              this.halfCheckedKeys = [];
              
              console.log('所有选中权限:', allPermissions);
            } else {
              this.$message.error('获取角色权限失败');
            }
          }).catch(err => {
            console.error('获取角色权限出错:', err);
            this.$message.error('获取角色权限失败');
          });
        } else {
          // 非超级管理员，获取当前用户的角色信息
          getCurrentUserRoles().then(res => {
            if (res.success && res.result && res.result.length > 0) {
              // 使用传入的角色ID查询该角色的权限
              queryRolePermission({roleId: this.roleId}).then((res)=>{
                console.log('角色权限响应:', res);
                if (res.success && res.result) {
                  // 保存所有权限ID
                  const allPermissions = [...res.result];
                  this.defaultCheckedKeys = [...allPermissions];
                  
                  // 初始化展开所有节点
                  this.expandedKeysss = this.allTreeKeys;
                  
                  // 在 checkStrictly 模式下，不需要区分半选状态，直接设置所有节点为选中
                  this.checkedKeys = allPermissions;
                  this.halfCheckedKeys = [];
                  
                  console.log('所有选中权限:', allPermissions);
                } else {
                  this.$message.error('获取角色权限失败');
                }
              }).catch(err => {
                console.error('获取角色权限出错:', err);
                this.$message.error('获取角色权限失败');
              });
            } else {
              console.log('当前用户没有任何角色');
              this.$message.error('当前用户没有任何角色，无法获取权限');
            }
          }).catch(err => {
            console.error('获取用户角色信息出错:', err);
            this.$message.error('获取用户角色信息失败');
          });
        }
      }
    },
    watch: {
      visible () {
        if (this.visible) {
          this.loadData();
        }
      }
    }
  }

</script>
<style lang="less" scoped>
  .drawer-bootom-button {
    position: absolute;
    bottom: 0;
    width: 100%;
    border-top: 1px solid #e8e8e8;
    padding: 10px 16px;
    text-align: right;
    left: 0;
    background: #fff;
    border-radius: 0 0 2px 2px;
  }

</style>